***************************************************************
* 04_robustness_analysis.do
* Afrobarometer Round 8 x GTD – Robustness Regressions
// Project: "The Impact of Terrorism on Democratic Support in Africa"
***************************************************************

version 18.0
clear all
set more off
set rmsg on
cap set scheme plotplain

* --------------------------------------------------------------
* Project root (robust to where the do-file is run from)
* --------------------------------------------------------------
local thisdo = c(filename)

* Fallback if c(filename) is empty (rare)
if "`thisdo'" == "" {
    global root "`c(pwd)'"
}
else {
    * Directory containing this do-file
    local dodir : dirname "`thisdo'"
    * Project root is parent of /dofile
    local root  : dirname "`dodir'"
    global root "`root'"
}

* If someone runs from inside /dofile (extra safety)
if substr("${root}", -6, 6) == "dofile" {
    global root = substr("${root}", 1, length("${root}")-6)
}


*--------------------------------------------------------------
* 0. PATHS (relative; no machine-specific paths)
*--------------------------------------------------------------

global data   "${root}/Original data"
global do     "${root}/dofile"
global out    "${root}/output"
global table  "${out}/tables"
global graph  "${out}/graphs"
global data_new  "${out}/Generated data"

cap mkdir "${out}"
cap mkdir "${table}"
cap mkdir "${graph}"
cap mkdir "${data_new}"


cap log close _all
log using "${out}/04_robustness_analysis.log", text replace name(rep)


*--------------------------------------------------------------
* 2. LOAD DATA
*--------------------------------------------------------------
use "${data}/R8_final.dta", clear
*--------------------------------------------------------------
* 3. COVARIATES & OUTCOME GROUPS
*--------------------------------------------------------------

* Demographic / covariate groups
global cvars_demographics ///
    age gender ///
    ib1.race_group ib1.religion ib1.urban_rural ib4.educ_group ///
    emp_group safety fearing_crime ///
    discuss_politics police_station soldiers_army piped_water

global cvars ///
    age gender ///
    race_group religion ///
    urban_rural educ_group emp_group ///
    safety fearing_crime ///
    discuss_politics police_station soldiers_army piped_water

* Outcome Groups
global outc demo_support auth_support demo_rated

//drop zdemo_support zauth_support

foreach v of varlist $outc {
    quietly summarize `v'
    generate z`v' = (`v' - r(min)) / (r(max) - r(min))
}

* Main z-outcomes used in this file (Table A.6, etc.)
global zoutcomes_gr1 zdemo_support zauth_support

* Quick checks
summarize $cvars
summarize $zoutcomes_gr1

***************************************************************
* 5. BALANCE TEST – Figure A.3
***************************************************************

* Treatment indicator(s)
global treatments time_zero

* Clear any svy settings
svyset, clear

* Entropy balancing weights for time_zero on main covariates
//drop balance_zero
ebalance time_zero $cvars, generate(balance_zero) targets(2)

svyset [pweight = balance_zero]

* Clear stored estimates
estimates clear

* Balance regressions: raw vs weighted
foreach y of varlist $treatments {
    quietly regress `y' $cvars_demographics
    estimates store T0_`y'
    
    quietly svy: regress `y' $cvars_demographics
    estimates store T1_`y'
}

* Plot balance: Panel A (unweighted) vs Panel B (weighted)
coefplot T0_time_zero || ///
         T1_time_zero, ///
    drop(_cons) xline(0, lpattern(solid)) ///
    byopts(row(1)) levels(99 95) ///
    bylabels("(A) Treatment all" "(B) Using weight") ///
    mlabel(cond(@pval<.001, "***", ///
           cond(@pval<.01, "**", ///
           cond(@pval<.05, "*", "")))) ///
    title(" ")

* Add titles for subplots
addplot 1: , b1title("Treatment all", size(small)) norescaling
addplot 2: , b1title("Using balance (entropy)") norescaling

* Save and export the balance graph
graph save   "${graph}/balance_afro.gph", replace
graph export "${graph}/balance_afro.eps", replace
graph export "${graph}/balance_afro.pdf", as(pdf) replace

***************************************************************
* 6. MAIN REGRESSION – Table A.6 (GTD, full sample)
***************************************************************

* Treatment indicator
global treatments time_zero 

* Entropy balancing weights
global zoutcomes zdemo_support zauth_support

capture erase "${table}/t1_e.xls"
capture erase "${table}/t1_e.rtf"
estimates clear
eststo clear

* Make sure esttab / eststo / estadd are available
cap which esttab
if _rc ssc install estout, replace

local models

foreach k of varlist $zoutcomes {
    
    *--------------------------
    * 1) Run model
    *--------------------------
    quietly svy: reg `k' i.time_zero $cvars i.cntrynum i.surveyyear
    
    *--------------------------
    * 2) Control-group summary
    *--------------------------
    quietly summarize `k' if time_zero == 0
    local m   = r(mean)
    local min = r(min)
    local max = r(max)
    local dp  = 2
    local fmt %`=`dp'+1'.`dp'f

    *--------------------------
    * 3) Short titles for table
    *--------------------------
    local short_title ""
    if "`k'" == "zdemo_support"    local short_title "Support for democracy"
    if "`k'" == "zauth_support"    local short_title "Reject authoritarianism"
 

    *--------------------------
    * 4) Add custom stats to e()
    *--------------------------
    quietly estadd scalar cmean = `m'
    quietly estadd scalar cmin  = `min'
    quietly estadd scalar cmax  = `max'
    quietly estadd local  pretreat "Yes"

    * Store model with nice title (for esttab)
    eststo, title("`short_title'")
    local models `"`models' `e(name)'"'

    *--------------------------
    * 5) Export the same coeffs via outreg2
    *--------------------------
    outreg2 using "${table}/t1_e.xls", ///
        keep(1.time_zero) ///
        bracket bdec(3) sdec(3) alpha(0.01, 0.05) ///
        ctitle(`k') label ///
        addstat(Control Mean, `: display `fmt' `m'') ///
        addtext(Covariates, Yes, Country FE, Yes, Survey Year FE, Yes) ///
        nocons append
}
   

*------------------------------------------
* PRINT TABLE TO RESULTS WINDOW
*------------------------------------------
esttab `models', ///
    keep(1.time_zero) ///
    b(3) se level(95) brackets ///
    star(* 0.05 ** 0.01 *** 0.001) ///
    label nonotes noobs nobaselevels ///
    coeflabels(1.time_zero "Terrorism exposure") ///
    mtitle ///
    stats(N r2 pretreat cmean, ///
          fmt(0 3 0 3 3 3) ///
          labels("Observations" "R^2" "Pre-treatment" "Control Mean" "Min" "Max")) ///
    compress

*-------------------------------*
* EXPORT CSV (same table)
*-------------------------------*
esttab `models' using "${table}/tableA6_gtd_fullsample.csv", replace csv ///
    keep(1.time_zero) ///
    coeflabels(1.time_zero "Terrorism exposure") ///
    b(3) se level(95) brackets ///
    star(* 0.05 ** 0.01 *** 0.001) ///
    mtitle ///
    label nonotes noobs nobaselevels ///
    stats(N r2 pretreat cmean cmin cmax, ///
          fmt(0 3 0 3 3 3) ///
          labels("Observations" "R^2" "Pre-treatment" "Control mean" "Min" "Max")) ///
    compress
***************************************************************
* 7. CROSS-COUNTRY REGRESSIONS – Figure A.4
*    Afrobarometer Round 8 x GTD, 2019–2021
***************************************************************

***************************************************************
* RESTRICT SAMPLE: COUNTRIES WITH BOTH TREATED & CONTROL
***************************************************************
preserve
    gen flag_0 = (time_zero == 0)
    gen flag_1 = (time_zero == 1)

    collapse (max) flag_0 flag_1, by(cntrynum)

    gen keep_country = (flag_0 == 1 & flag_1 == 1)
    keep if keep_country

    keep cntrynum
    tempfile good_cntryr8gtd
    save `good_cntryr8gtd'
restore

* Keep only countries that have both time_zero values
merge m:1 cntrynum using `good_cntryr8gtd', keep(match) nogen

* Save restricted dataset (used later for country plots)
save "${data_new}/good_cntryr8gtd.dta", replace

//use "${data_new}/good_cntryr8gtd.dta", clear

* Outcomes for plots
local outcome "zdemo_support zauth_support zdemo_rated"

* Get list of country codes actually in the restricted sample
levelsof cntrynum, local(ctrylist)

local graphlist
estimates clear

foreach cid of local ctrylist {
    
    * Get country name from value label, if available
    local cname : label (cntrynum) `cid'
    if "`cname'" == "" local cname "Country `cid'"
    
    local estlist
    
    * Run regressions per outcome for this country
    foreach var of local outcome {
        quietly capture svy: regress `var' i.time_zero $cvars i.surveyyear if cntrynum == `cid'
        if !_rc {
            estimates store est_`var'_`cid'
            local estlist `estlist' est_`var'_`cid'
        }
    }
    
    * If at least one regression succeeded, draw a country plot
    if "`estlist'" != "" {
        local gname gr_`cid'
        
        capture noisily coefplot `estlist', ///
            keep(1.time_zero) ///
            drop(_cons) ///
            xline(0, lcolor(gs10)) ///
            coeflabels(1.time_zero = " ") ///
			plotlabels("Support for democracy" ///
                       "Rejection of authoritarianism" ///
                       "Democracy rating") ///
            legend(rows(1)) ///
            title("`cname'", size(medsmall)) ///
            legend(off) ///
            ylabel(, labsize(small)) ///
            xlabel(-0.4(0.2)0.25, labsize(small)) ///
            name(`gname', replace) ///
            ysize(2) xsize(5)
        
        capture confirm graph `gname'
        if !_rc {
            local graphlist `graphlist' `gname'
        }
    }
}

* Combine all successfully created graphs
	grc1leg gr_1 gr_3 gr_5 gr_8 gr_11, ///
cols(3) imargin(2 2 2 2) xsize(8) ysize(7)

graph save   "${graph}/DV1_cntryr8gtd.gph", replace
graph export "${graph}/DV1_cntryr8gtd.pdf", as(pdf) replace
***************************************************************
* END OF DO-FILE
***************************************************************
